<?php
	session_start();
	require_once("MoneyFactory.class.php"); 
	require_once("MoneyOps.class.php");
?>

<html>
	<head>
		<title>Porte Monnaie - itération 1</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	</head>
	<body>
		<?php

			if ( !isset($_SESSION['devise'])) {
				$_SESSION['devise'] = array();
			}

			if ( isset($_POST['v1']) && isset($_POST['devise']) ) {

				$valueNote = 0;
				$valuePiece = 0;
				$currency;

				// billets ou pieces
				if ($_POST["type"] === "valueNote") {
					$valueNote = $_POST['v1'];
				} else if ($_POST["type"] === "valuePiece") {
					$valuePiece = $_POST['v1'];
				}

				// money
				$currency = $_POST["devise"];
				$moneyToAdd = MoneyFactory::getDefaultFactory()->createMoney($valueNote, $valuePiece, $currency);

				if ( isset($_SESSION[$currency]) ) {
					// la money existe deja dans la session
					$currentMoney = unserialize($_SESSION[$currency]);
					$newMoney = MoneyOps::add($currentMoney, $moneyToAdd);
					$_SESSION[$currency] = serialize($newMoney);
				} else {
					// la money n'existe pas encore dans la session
					$_SESSION[$currency] = serialize($moneyToAdd);
					array_push($_SESSION['devise'], $currency);
				}	
			}

			echo "etat de votre porte monnaie :"; echo"<br/>";
			foreach ($_SESSION['devise'] as $devise) {
				$money = unserialize($_SESSION[$devise]);
				echo $money->getValueNote() . " " . $money->getCurrency() . " en billets et " . $money->getValuePiece() . " " . $money->getCurrency() . " en pieces";
				echo "<br/>";
			}
		?>
		<hr width='20%' align='left'/>
		<form action='index.php' method='post' id='form'>
		<table>
			<tr>
				<td>Valeur</td>
				<td>Devise</td>
				<td>Type</td>
			</tr>
			<tr>
				<td><input type='text' id='v1' name='v1'/></td>
				<td>
					<input type="text" id="devise" name="devise">
				</td>
				<td>
					<select name="type" id="type">
						<option value="valueNote">billets</option>
						<option value="valuePiece">pieces</option>
					</select>
				</td>
			  <td colspan='5' align='right'><input type='submit' value='Ajouter'/></td>		
			</tr>
		</table>
		</form>
	</body>
</html>
